<template>
    <div class="chat-container">
      <div class="message-list">
        <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
          <div class="role">{{ msg.role === 'user' ? '你' : 'AI助手' }}</div>
          <div class="content" v-html="renderMarkdown(msg.content)"></div>
        </div>
        <div v-if="loading" class="loading-indicator">AI正在思考...</div>
      </div>
      
      <div class="input-area">
        <el-input
          v-model="inputQuestion"
          placeholder="请输入你的问题"
          :disabled="loading"
          @keyup.enter="sendQuestion"
        >
          <template #append>
            <el-button 
              type="primary" 
              @click="sendQuestion"
              :loading="loading"
            >
              发送
            </el-button>
          </template>
        </el-input>
      </div>
    </div>
  </template>
  
  <script setup>

  import { ElMessage } from 'element-plus'
  import { streamChat } from '@/utils/streamRequest'
  import { marked } from 'marked'
  import { ref, onBeforeUnmount } from 'vue'
  import router from '@/router';
  
  const inputQuestion = ref('')
  const messages = ref([])
  const loading = ref(false)
  let cancelStream = null
  
  // 发送问题
  const sendQuestion = async () => {
    if (!inputQuestion.value.trim()) {
      ElMessage.warning('请输入问题')
      return
    }
  
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录')
      return router.push('/login')
    }
  
    // 添加用户消息
    messages.value.push({
      role: 'user',
      content: inputQuestion.value
    })
  
    // 添加空的AI消息占位
    const aiMessageIndex = messages.value.push({
      role: 'assistant',
      content: ''
    }) - 1
  
    loading.value = true
    const question = inputQuestion.value
    inputQuestion.value = ''
  
    try {
      cancelStream = await streamChat(
        { question, token },
        (chunk) => {
          // 追加内容到AI消息
          messages.value[aiMessageIndex].content += chunk
        }
      )
    } catch (error) {
      ElMessage.error('请求失败: ' + error.message)
      messages.value[aiMessageIndex].content = '抱歉，回答问题时出错'
    } finally {
      loading.value = false
    }
  }
  
  // Markdown渲染
  const renderMarkdown = (text) => {
    return marked(text || '')
  }
  
  // 组件卸载时取消请求
  onBeforeUnmount(() => {
    if (cancelStream) {
      cancelStream()
    }
  })
  </script>
  
  <style scoped>
  .chat-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    height: 100vh;
    display: flex;
    flex-direction: column;
  }
  
  .message-list {
    flex: 1;
    overflow-y: auto;
    padding-bottom: 80px;
  }
  
  .message {
    margin-bottom: 20px;
    padding: 15px;
    border-radius: 8px;
    background: #f5f5f5;
  }
  
  .message.user {
    background: #e3f2fd;
    margin-left: 20%;
  }
  
  .message.assistant {
    background: #f1f1f1;
    margin-right: 20%;
  }
  
  .role {
    font-weight: bold;
    margin-bottom: 5px;
    color: #666;
  }
  
  .content {
    line-height: 1.6;
  }
  
  .input-area {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    background: white;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    z-index: 100;
  }
  
  @media (min-width: 800px) {
    .input-area {
      left: 50%;
      transform: translateX(-50%);
      width: 800px;
      border-radius: 8px;
      bottom: 20px;
    }
  }
  
  .loading-indicator {
    text-align: center;
    color: #999;
    padding: 10px;
  }
  </style>